//
//  Timer.m
//  YanXiuWang
//
//  Created by 慧趣小歪 on 17/1/10.
//  Copyright © 2017年 小分队. All rights reserved.
//

#import "Timer.h"

@interface Timer ()

@property (nonatomic, assign) NSTimeInterval lastTime;
@property (nonatomic, strong) dispatch_block_t backThread;

@end

@implementation Timer

- (void)setEnabled:(BOOL)enabled {
    _enabled = enabled;
    if (!enabled) return;
    if (_backThread != nil) return;
    
    // 初次启动时间是 delay 秒后
    [self reset];

    __weak typeof(self) weakSelf = self;
    
    _backThread = ^{
        while (weakSelf.enabled) {
            NSTimeInterval currentTime = CACurrentMediaTime();
            if (currentTime - weakSelf.lastTime > weakSelf.interval && weakSelf.action != nil) {
                weakSelf.lastTime = currentTime;
                [weakSelf.target performSelectorOnMainThread:weakSelf.action withObject:weakSelf.tag ?: weakSelf waitUntilDone:YES];
            }
            [NSThread sleepForTimeInterval:0.05];
        }
    };
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), _backThread);
}

- (void)reset {
    // 初次启动时间是 delay 秒后
    _lastTime = CACurrentMediaTime() + _delay - _interval;
}

@end
